package com.yunshipei.ui.fragment;


import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.yunshipei.common.Globals;
import com.yunshipei.core.manager.TabManager;
import com.yunshipei.core.utils.SystemUtils;
import com.yunshipei.enterplorer.R;
import com.yunshipei.model.MainExtraBean;
import com.yunshipei.model.YspEvent;
import com.yunshipei.ui.view.TabBar;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.rong.app.fragment.ContactsFragment;
import io.rong.eventbus.EventBus;

public class NavigationFragment extends BaseNavFragment {

    private static final String ARGS_IS_CACHE_DATA = "com.enterplorer.is.cache.data";
    private static final String ARGS_NAVIGATION_DATA = "com.enterplorer.navigation.data";

    public static final int FIRST = 0;
    public static final int SECOND = 1;
    public static final int THIRD = 2;
    public static final int FOURTH = 3;

    @Bind(R.id.view_tab_bar)
    protected TabBar mTabBar;
    private NavigationInteractionListener mNavigationInteractionListener;

    private Context mContext;
    private Fragment mFragments[];
    private boolean isFromCache = false;
    private MainExtraBean mMainExtraBean;

    public static NavigationFragment newInstances(MainExtraBean mMainExtraBean) {
        NavigationFragment navigationFragment = new NavigationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_NAVIGATION_DATA, mMainExtraBean);
        navigationFragment.setArguments(bundle);
        return navigationFragment;
    }

    public static NavigationFragment newInstances(MainExtraBean mMainExtraBean, boolean cacheData) {
        NavigationFragment navigationFragment = new NavigationFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(ARGS_NAVIGATION_DATA, mMainExtraBean);
        bundle.putBoolean(ARGS_IS_CACHE_DATA, cacheData);
        navigationFragment.setArguments(bundle);
        return navigationFragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof NavigationInteractionListener) {
            mNavigationInteractionListener = (NavigationInteractionListener) context;
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mNavigationInteractionListener = null;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        EventBus.getDefault().register(this);
        isFromCache = getArguments().getBoolean(ARGS_IS_CACHE_DATA);
        mMainExtraBean = (MainExtraBean) getArguments().getSerializable(ARGS_NAVIGATION_DATA);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_navigation, container, false);
        view.invalidate();
        ButterKnife.bind(this, view);
        return view;
    }

    private int lastPosition = -1;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        FragmentManager fm = getChildFragmentManager();
        if (SystemUtils.isPad(mContext)) {
            mFragments = new Fragment[2];
            mFragments[FIRST] = fm.findFragmentByTag(H5HomeFragment.class.getName());
            if (mFragments[FIRST] == null) {
                mFragments[FIRST] = H5HomeFragment.newInstance(mMainExtraBean);
            }
            mFragments[SECOND] = fm.findFragmentByTag(PadMeFragment.class.getName());
            if (mFragments[SECOND] == null) {
                mFragments[SECOND] = PadMeFragment.newInstance(mMainExtraBean);
            }
            mTabBar.initMainTab(mContext, Globals.PAD_TABS);
            //新需求：产品要求pad版需要有账号被踢下线功能，所以将MessageFragment添加到布局以使IM正常加载
            if (!isFromCache) {
                Fragment fragment = fm.findFragmentByTag(MessageFragment.class.getName());
                if (fragment == null) {
                    fragment = MessageFragment.newInstance(mMainExtraBean);
                    getChildFragmentManager().beginTransaction().add(R.id.fl_navigation_window, fragment, MessageFragment.class.getName()).commit();
                }
                if (!fragment.isHidden()) {
                    getChildFragmentManager().beginTransaction().hide(fragment).commit();
                }
            }
        } else {
            mFragments = new Fragment[3];
            boolean h5 = h5Client();
            mFragments[FIRST] = fm.findFragmentByTag(h5 ? H5HomeFragment.class.getName() : HomeFragment.class.getName());
            if (mFragments[FIRST] == null) {
                mFragments[FIRST] = h5 ? H5HomeFragment.newInstance(mMainExtraBean) : HomeFragment.newInstance(mMainExtraBean);
            }
//            mFragments[SECOND] = getChildFragmentManager().findFragmentByTag(MessageFragment.class.getName());
//            if (mFragments[SECOND] == null) {
//                mFragments[SECOND] = MessageFragment.newInstance(mMainExtraBean);
//            }
//            mFragments[SECOND] = getChildFragmentManager().findFragmentByTag(h5 ? H5ContactFragment.class.getName() : ContactsFragment.class.getName());
//            if (mFragments[SECOND] == null) {
                mFragments[SECOND] =  ContactsFragment.newInstances(mMainExtraBean);
            //h5 ? H5ContactFragment.newInstance(mMainExtraBean) :
            //}
            mFragments[THIRD] = getChildFragmentManager().findFragmentByTag(h5 ? H5CustomFragment.class.getName() : MeFragment.class.getName());
            if (mFragments[THIRD] == null) {
                mFragments[THIRD] = h5 ? H5CustomFragment.newInstance(mMainExtraBean) : MeFragment.newInstance(mMainExtraBean);
            }
            if (!isFromCache && !mFragments[SECOND].isAdded()) {
                //因为消息的fragment需要立即初始化
                getChildFragmentManager().beginTransaction().add(R.id.fl_navigation_window, mFragments[SECOND], MessageFragment.class.getName()).commit();
            }
            mTabBar.initMainTab(mContext, Globals.TABSS);
        }
        mTabBar.setOnTabChangeListener(new TabBar.OnTabChangeListener() {
            @Override
            public void onTabChange(int position) {
                if (position != lastPosition) {
                    lastPosition = position;
                    if (position == FIRST) {
                        mNavigationInteractionListener.getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                    } else {
                        mNavigationInteractionListener.getDrawer().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                    }
                    FragmentManager fm = getChildFragmentManager();
                    FragmentTransaction ft = fm.beginTransaction();
                    Fragment currentFragment = mFragments[position];
                    if (!currentFragment.isAdded()) {
                        ft.add(R.id.fl_navigation_window, currentFragment, currentFragment.getClass().getName());
                    }
                    for (int i = 0; i < mFragments.length; i++) {
                        Fragment fragment = mFragments[i];
                        if (position == i) {
                            ft.show(fragment);
                        } else {
                            if (fragment.isAdded() && !fragment.isHidden()) {
                                ft.hide(fragment);
                            }
                        }
                    }
                    ft.commit();
                    fm.executePendingTransactions();
                }
            }
        });
        mTabBar.setCurrentTab(FIRST);
    }

    public boolean canGoBack() {
        if (2 == lastPosition || 3 == lastPosition) {
            Fragment fragment = mFragments[lastPosition];
            if (fragment instanceof H5BaseFragment) {
                H5BaseFragment h5BaseFragment = (H5BaseFragment) fragment;
                return h5BaseFragment.pageCanGoBack();
            }
        }
        return false;
    }

    public void goBack() {
        if (2 == lastPosition || 3 == lastPosition) {
            Fragment fragment = mFragments[lastPosition];
            if (fragment instanceof H5BaseFragment) {
                H5BaseFragment h5BaseFragment = (H5BaseFragment) fragment;
                h5BaseFragment.pageGoBack();
            }
        }

    }

    private boolean h5Client() {
        if (SystemUtils.isPad(mContext)) {
            return true;
        }
        int managerCode = mMainExtraBean.getManagerCode();
        return managerCode >= 2;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    //如果缓存加载失败，则使用这个Fragment做为入口，测试需要初始化IM的Fragment
    @Override
    public void resetIM() {
        Fragment msgFragment = mFragments[SECOND];
        if (!msgFragment.isAdded()) {
            getChildFragmentManager().beginTransaction().add(R.id.fl_navigation_window, msgFragment, msgFragment.getClass().getName()).hide(msgFragment).commit();
        }
    }

    //消息数目变化
    public void onEventMainThread(YspEvent.MessageNumEvent event) {
        int count = event.getNum();
        mTabBar.setMessageCount(count);
    }

    //清空聊天记录刷新消息数目
    public void onEventMainThread(YspEvent.MessageCountClearEvent event) {
        mTabBar.setMessageCount(0);
    }

    //切换到消息或九宫格页面
    public void onEventMainThread(YspEvent.TabChangeEvent event) {
        mTabBar.setCurrentTab(event.getPosition());
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!isHidden()) {
            EventBus.getDefault().post(new YspEvent.ConfigProxy());
        } else {
            //隐藏是保存当前首页的snapshot
            new Thread(new Runnable() {
                @Override
                public void run() {
                    saveHomeSnapshot(true);
                }
            }).start();
        }
    }

    @Override
    public String captureHomeWebView() {
        DrawerLayout drawerLayout = mNavigationInteractionListener.getDrawer();
        boolean viewShowing = !isHidden() && !mFragments[FIRST].isHidden() && drawerLayout != null && !drawerLayout.isDrawerOpen(Gravity.LEFT);
        return saveHomeSnapshot(viewShowing);
    }

    private String saveHomeSnapshot(boolean reCreate) {
        if (h5Client()) {
            H5HomeFragment h5HomeFragment = (H5HomeFragment) mFragments[FIRST];
            return h5HomeFragment.getHomeWebViewCaptureURL(reCreate);
        } else {
            HomeFragment homeFragment = (HomeFragment) mFragments[FIRST];
            return homeFragment.getHomeWebViewCaptureURL(reCreate);
        }
    }

    public interface NavigationInteractionListener {
        DrawerLayout getDrawer();
    }

    @Override
    public void onDestroyView() {
        if (mTabBar != null) {
            mTabBar.unRegistListener();
        }
        if (mFragments != null && mFragments.length > 0) {
            for (int i = 0; i < mFragments.length; i++) {
                mFragments[i] = null;
            }
            mFragments = null;
        }
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }
}
